from PIL import Image
from StringIO import StringIO

# This function creates a PIL Image from raw image data.
def load_image_from_data(data):
    try:
        sio = StringIO(data)
        image = Image.open(sio)
    except Exception, e:
        raise Exception('Error loading image data, msg="%s"'%e.message)    
    return image
    
# This function extracts the raw image data from a PIL Image. 
def get_data_from_image(image, format = None):
    sio = StringIO()
    image.save(sio, format)
    return sio.getvalue()

def perform(**parts):
    # Sort the parts by their key-name.
    sorted_parts = []
    for partno in range(0, len(parts)):
        sorted_parts.append(load_image_from_data(parts['part%i'%partno]))
    
    # Find the height and width of the image.
    width = sorted_parts[0].size[0]
    height = 0
    for part in sorted_parts:
        height += part.size[1]
    
    # Create a new Image and inject the data.
    image = Image.new('RGB', (width, height), None)
    
    # Paste the image parts into the new image.
    current_height = 0
    for partno in range(0, len(sorted_parts)):
        image.paste(sorted_parts[partno], (0, current_height))
        current_height += sorted_parts[partno].size[1]

    # Return the image data.
    return get_data_from_image(image, sorted_parts[0].format)
